package com.own.business.system.user.controller.user.open;

import com.own.business.system.user.business.service.SystemUserService;
import com.own.business.system.user.controller.user.entity.form.UpdatePasswordForm;
import com.own.component.common.login.util.SessionUserUtil;
import com.own.component.store.core.util.base.RsaKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * UserSystemUserLoginOpen
 *
 * @author chenxueli
 * @date 2023-11-30 10:54:00
 */
@Slf4j
@Component
public class UserSystemUserLoginOpen {

    @Resource
    private SystemUserService systemUserService;

    @Resource
    private RsaKeyUtil rsaKeyUtil;

    /**
     * 修改密码
     *
     * @param form 表单
     * @return ResultModel<Boolean>
     */
    public Boolean updatePassword(UpdatePasswordForm form) {
        form.check();
        // 解密加密的密码信息，如果没有key，表示为不加密登录
        if (StringUtils.isNotBlank(form.getKey())) {
            if (StringUtils.isNotBlank(form.getOldPassword())) {
                var oldPassword = rsaKeyUtil.decrypt(form.getKey(), form.getOldPassword(), false);
                form.setOldPassword(oldPassword);
            }
            var password = rsaKeyUtil.decrypt(form.getKey(), form.getPassword(), true);
            form.setPassword(password);
        }
        var loginUser = SessionUserUtil.getLoginUser();
        systemUserService.changePassword(loginUser.userId(), form.getPassword(), form.getOldPassword());
        // 返回信息
        return true;
    }

}
